package cn.stylefeng.guns.core.schedule;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.sys.core.properties.TaskConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.LogUtil;
import cn.stylefeng.guns.sys.modular.rest.entity.NameRelation;
import cn.stylefeng.guns.sys.modular.rest.service.NameRelationService;
import cn.stylefeng.guns.sys.modular.system.db2.service.BusinessService;
import cn.stylefeng.guns.sys.modular.system.model.params.ProDataViewParam;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.UnknownHostException;
import java.util.*;

/**
 * 供应链相关接口的定时任务
 */
@Component
public class DsstoreBillScheduledTask {
    private Logger logger = LoggerFactory.getLogger(DsstoreBillScheduledTask.class);
    @Resource
    private TaskConfig taskConfig;
    @Resource
    private BtyShopService btyShopService;
    @Resource
    private ItemUnitService itemUnitService;
    @Resource
    private BusinessService businessService;
    @Resource
    private DsstoreBillService dsstoreBillService;
    @Resource
    private BtyShopTreeService btyShopTreeService;
    @Resource
    private ItemInterfaceService itemInterfaceService;
    @Resource
    private BusinessMonthService businessMonthService;
    @Resource
    private DsstoreBillRiceService dsstoreBillRiceService;
    @Resource
    private BusinessSalesMonthService businessSalesMonthService;
    @Resource
    private DsstoreBillDeliveryService dsstoreBillDeliveryService;


    public DsstoreBillScheduledTask() throws UnknownHostException {
    }


    /**
     * 每天晚上2点执行
     * 初始化门店bty_shop,及bty_shop_tree数据
     */
    @XxlJob("cshmdTreeDataJob")
//    @Scheduled(cron = "0 0 2/23 * * ? ")
    public void initShopData() {
        try {
            logger.info("门店数据入库-开始执行");
            btyShopService.initShopData();
            logger.info("门店数据入库结束-结束执行");
            //初始化门店树
            btyShopTreeService.initShopTeeData();
        } catch (Exception e) {
            logger.info("初始化门店树数据失败");
            e.printStackTrace();
        }
    }

    /**
     * 门店库存流水数据
     */
//    @Scheduled(cron = "0 0 3 * * ?")
    public void initDsstorebillData() {
        if ("y".equals(taskConfig.getRun())) {
            try {
                Date date = new Date();
                //获取前一天的数据
                String yearstoday = DateUtil.getYearstoday(date);
                List<String> dateList = new ArrayList<>();
                dateList.add(DateUtil.getNowDate());
                dateList.add(yearstoday);
                logger.info("门店库存流水定时任务-开始执行数据写入,日期：{}", date);
                Map<String, Integer> map = dsstoreBillService.initDsstorebillData(dateList);
                logger.info("门店库存流水定时任务-结束执行数据写入,{}", map.toString());
            } catch (Exception e) {
                logger.info("门店库存流水定时任务执行失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除垃圾数据
     */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteDsstorebillDataByDays() {
        if ("y".equals(taskConfig.getRun())) {

            try {

                String firstDay = DateUtil.getMonthFirstDayByAgo(1);
                Date date = new Date();
                String thisDay = DateUtil.getStrDate(date);
                List<String> dateList = DateUtil.getBetweenDate(firstDay, thisDay);
                logger.info("门店库存流水定时任务-删除垃圾数据,开始，日期：{}", dateList.toString());
                dsstoreBillService.deleteDsstorebillDataByDays(dateList);
                logger.info("门店库存流水定时任务-删除垃圾数据，结束");
            } catch (Exception e) {
                logger.info("门店库存流水定时任务，删除垃圾数据失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除垃圾数据-根据删除单据接口
     */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteDsstorebillDataByDelInterface() {
        if ("y".equals(taskConfig.getRun())) {

            try {

                String firstDay = DateUtil.getMonthFirstDayByAgo(1);
                Date date = new Date();
                String thisDay = DateUtil.getStrDate(date);
                List<String> dateList = DateUtil.getBetweenDate(firstDay, thisDay);
                logger.info("门店库存流水定时任务-删除垃圾数据,开始，日期：{}", dateList.toString());
                dsstoreBillService.deleteDsstorebillDataByDelInterface(dateList);
                logger.info("门店库存流水定时任务-删除垃圾数据，结束");
            } catch (Exception e) {
                logger.info("门店库存流水定时任务，删除垃圾数据失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 大米消耗1-门店库存流水集市数据导入-大米盘亏数据
     */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void initDsstorebillRiceData() {

        try {
            if ("y".equals(taskConfig.getRun())) {
                //List<String> dateList5 = DateUtil.getBetweenDate("2021-06-01", "2021-06-02");
                Date date = new Date();
                //获取前两天数据
                List<String> dateList = DateUtil.getTwoDaysAgoByDate(date);

                logger.info("门店库存流水定时任务-大米盘亏-开始执行数据写入,日期：{}", dateList.toString());
                LinkedHashMap<String, Integer> map5 = dsstoreBillRiceService.initDsstoreBillRiceData(dateList);
                logger.info("门店库存流水定时任务-大米盘亏-结束执行数据写入,{}", map5.toString());

            }
        } catch (Exception e) {
            logger.info("门店库存流水定时任务，写入数据失败");
            e.printStackTrace();
        }
    }

    /**
     * 删除垃圾数据
     */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteDsstorebillRiceDataByDays() {
        if ("y".equals(taskConfig.getRun())) {

            try {

                String firstDay = DateUtil.getMonthFirstDayByAgo(1);
                Date date = new Date();
                String thisDay = DateUtil.getStrDate(date);
                List<String> dateList = DateUtil.getBetweenDate(firstDay, thisDay);
                logger.info("门店库存流水定时任务-删除垃圾数据,开始，日期：{}", dateList.toString());
                dsstoreBillRiceService.deleteDsstorebillRiceDataByDays(dateList, 0);
                logger.info("门店库存流水定时任务-删除垃圾数据，结束");
            } catch (Exception e) {
                logger.info("门店库存流水定时任务，删除垃圾数据失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除垃圾数据-根据删除单据接口
     */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteDsstorebillRiceDataByDelInterface() {
        if ("y".equals(taskConfig.getRun())) {

            try {

                String firstDay = DateUtil.getMonthFirstDayByAgo(1);
                Date date = new Date();
                String thisDay = DateUtil.getStrDate(date);
                List<String> dateList = DateUtil.getBetweenDate(firstDay, thisDay);
                logger.info("门店库存流水定时任务-删除垃圾数据,开始，日期：{}", dateList.toString());
                dsstoreBillRiceService.deleteDsstorebillDataByDelInterface(dateList);
                logger.info("门店库存流水定时任务-删除垃圾数据，结束");
            } catch (Exception e) {
                logger.info("门店库存流水定时任务，删除垃圾数据失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 大米消耗3-录入上月各个门店的就餐人数数据
     * 每月首日一号凌晨5点执行
     */
//    @Scheduled(cron = "0 0 5 1 * ?")
    public void initPeopleQtyData() {
        if ("y".equals(taskConfig.getRun())) {

            try {
                ProDataViewParam param2 = new ProDataViewParam();
                String lastMonth = DateUtil.getLastMonthStr();

                String startTime = DateUtil.getFisrtDayOfMonth(lastMonth) + " 04:00:00";
                String endTime = DateUtil.get4OclockByDay(DateUtil.getLastDayByMonth(lastMonth));
                param2.setStartTime(startTime);
                param2.setEndTime(endTime);

                List<Map<String, Object>> businessDataByParam = businessService.findPeopleQtyByParam(param2);
                businessMonthService.insertData(lastMonth, businessDataByParam);
            } catch (Exception e) {
                logger.info("定时任务失败，录入就餐人数数据失败");
                e.printStackTrace();
            }
        }
    }


    /**
     * 大米消耗4-外卖主食数据 录入上月各个门店的 外卖主食数据 -每份4kg大米
     * 每月首日一号凌晨5点执行
     */
//    @Scheduled(cron = "0 0 5 1 * ?")
    public void initTakeawayRiceData() {
        if ("y".equals(taskConfig.getRun())) {

            try {
                ProDataViewParam param2 = new ProDataViewParam();
                String lastMonth = DateUtil.getLastMonthStr();

                String startTime = DateUtil.getFisrtDayOfMonth(lastMonth) + " 04:00:00";
                String endTime = DateUtil.get4OclockByDay(DateUtil.getLastDayByMonth(lastMonth));
                param2.setStartTime(startTime);
                param2.setEndTime(endTime);

                List<Map<String, Object>> businessDataByParam = businessService.findTakeawayRiceDataByParam(param2);
                businessSalesMonthService.insertData(lastMonth, businessDataByParam);
            } catch (Exception e) {
                logger.info("定时任务失败，录入门店主食数据，失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 门店库存流水初期单定时任务
     */
//    @Scheduled(cron = "0 0 5 * * ?")
    public void initDsstorebillChuQiDanData() {
        //每天凌晨3点获取前一天的数据入库
        try {

            logger.info("门店库存流水初期单定时任务-开始");
            ResponseData data = dsstoreBillService.initDsstorebillChuQiDanData();
            logger.info("门店库存流水初期单定时任务-结束");
        } catch (Exception e) {
            logger.info("门店库存流水初期单定时任务，执行失败");
            e.printStackTrace();
        }
    }

    /**
     * 连锁配送台账表-发货统计表-财务报表-定时任务-录入上个月的数据（中心统配出库、中心统配返库）
     * 一个月执行一次，每个月1号的凌晨6点执行一次
     */
//    @Scheduled(cron = "0 0 6 1 1/1 ?")
    public void initDsstorebillDelData() {
        try {
            if ("y".equals(taskConfig.getRun())) {
                //某月前
                int monbefore = 1;
                String firstDayByAgo = DateUtil.getMonthFirstDayByAgo(monbefore);
                String lastDayByAgo = DateUtil.getMonthLastDayByAgo(monbefore);

                List<String> dateList = DateUtil.getBetweenDate(firstDayByAgo, lastDayByAgo);
                logger.info("配送台账定时任务-开始执行数据写入,日期：{}", dateList.toString());
                dsstoreBillDeliveryService.initDsstoreBillData(dateList);
                logger.info("配送台账定时任务-结束执行数据写入");

            }
        } catch (Exception e) {
            logger.info("配送台账定时任务，写入数据失败");
            e.printStackTrace();
        }
    }

    /**
     * 连锁配送台账表-发货统计表-财务报表-定时任务
     */
//    @Scheduled(cron = "0 0 12 * * ?")
    public void initItemUnitData() {
        try {
            if ("y".equals(taskConfig.getRun())) {
                logger.info("初始化品项数据1-1-开始执行");
                itemInterfaceService.initIntemInferfaceData();
                logger.info("初始化品项数据1-1-结束执行");

                logger.info("初始化品项单位数据1-2-开始执行");
                itemUnitService.initItemUnitData();
                logger.info("初始化品项单位数据1-2-结束执行");
            }
        } catch (Exception e) {
            logger.info("配送台账定时任务，写入数据失败");
            e.printStackTrace();
        }
    }


}
